package com.oc.mba.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.oc.mba.entity.OcDevices;
import com.oc.mba.entity.OcOrder;
import com.oc.mba.entity.OcPaper;
import com.oc.mba.service.DeviceService;
import com.oc.mba.service.PaperService;
import com.oc.mba.service.PaymentService;
import com.oc.mba.util.CommConsts;
import com.oc.mba.util.CommLog;
import com.oc.mba.util.JsonUtil;
import com.oc.mba.util.ResultCode;

/**
 * 
 * 支付控制
 * @author unidw
 *
 */
@Controller
public class PaymentController extends BaseController implements IController {
	
	public static final String VIP_TAG = "v";
	public static final String PAPER_TAG = "p";
	private static final CommLog logger = new CommLog(PaymentController.class);
	@Autowired
	private PaymentService paymentService;
	@Autowired
	private DeviceService deviceService;
	@Autowired
	private PaperService paperService;
	
	@Override
	public String progress(WrappedReq wReq, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		logger.info("req=" + wReq);
		Map<String, Object> result = new HashMap<String, Object>();
		// 当前时间戳
		Timestamp timestamp = new Timestamp(System.currentTimeMillis());
		Integer deviceID = wReq.getContent().getInt(CommConsts.DEVICE_ID);
		// 有效的设备ID
		if (deviceID!=null && deviceID > 0) {
			OcDevices device = deviceService.findById(deviceID);
			// 购买试卷，生成订单号
			if (wReq.getSignID().equals("301")) {
				Integer paperId = wReq.getContent().getInt(CommConsts.PAPER_ID);
				OcPaper paper = paperService.findPaper(paperId);
				String orderID = PAPER_TAG + timestamp.getTime();
				OcOrder order = new OcOrder();
				order.setOrderId(orderID);
				order.setDeviceId(deviceID);
				order.setPaperId(paperId);
				order.setOrderCost(paper.getPaperPrice());
				order.setFinished((short)0);
				order.setOrderTime(timestamp);
				paymentService.save(order);
				result.put(CommConsts.RESULT_FLAG, ResultCode.SUCCESS);
				result.put(CommConsts.ORDER_DID, order.getId());
				result.put(CommConsts.ORDER_ID, orderID);
				return JsonUtil.jsonMTS(result);
			}
			// 购买会员，生成订单号
			else if (wReq.getSignID().equals("302")) {
				String orderID = VIP_TAG + timestamp.getTime();
				OcOrder order = new OcOrder();
				order.setOrderId(orderID);
				order.setDeviceId(deviceID);
				// TODO Const VIP Price
				order.setOrderCost(30.00);
				order.setFinished((short)0);
				order.setOrderTime(timestamp);
				paymentService.save(order);
				
				result.put(CommConsts.RESULT_FLAG, ResultCode.SUCCESS);
				result.put(CommConsts.ORDER_ID, orderID);
				return JsonUtil.jsonMTS(result);
			}
			else if (wReq.getSignID().equals("303")) {
				String deviceKey = "4df20f0e51be28a8";
				String orderStr = wReq.getContent().getString("orderStr");
				String orderDIDs[] = orderStr.split(",");
				List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
				for (String orderDID : orderDIDs) {
					logger.info("check order status. orderDID=" + orderDID);
					Map<String, Object> orderMap = new HashMap<String, Object>();
					if (orderDID!=null && !orderDID.equals("")) {
						orderMap.put("orderDID", orderDID);
						orderMap.put("orderStatus", queryOrderState(Integer.valueOf(orderDID)));
						resultList.add(orderMap);
					}
					else {
						logger.info("check order status. orderDID is empty. orderDID=" + orderDID);
					}
				}
				result.put(CommConsts.RESULT_FLAG, ResultCode.SUCCESS);
				result.put("orderList", resultList);
				String resultJSON = JsonUtil.jsonMTS(result);
				logger.info("check order status. result=" + resultJSON);
				return resultJSON;
			}
		}
		// 设备ID无效
		else {
			
		}
		// TODO 验证用户
		return JsonUtil.jsonMTS(result);
	}

	/**
	 * 查询订单状态
	 * @param orderID 订单ID
	 * @return 0:未付款;1:已经付款;-1:未知订单状态l;-2:订单不存在
	 */
	private String queryOrderState(Integer orderID) {
		OcOrder order = paymentService.findOrderByID(orderID);
		if (order != null) {
			// 未付款
			if (order.getFinished() == 0) {
				return "0";
			}
			// 已经付款成功
			else if(order.getFinished() == 1){
				return "1";
			}
			else {
				return "-1";
			}
		}else {
			return "-2";
		}
	}

}
